/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001, 2005, 2007 Free Software Foundation, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General
   Public License along with this library; if not, write to the
   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301 USA */

/**
 * \file timer.cc
 * \author Ice and Magic
 * \date 21 Avril 2011
 *
 */


#include <iostream>
#include <sys/time.h>
#include "timer.h"
using namespace std;
void	
timer::print_machine(){
cout<<"\nElapsed time :";
cout<<"\nCumulative CPU cycles : "<<cycle_end-cycle_start;
cout<<"\nCumulative CPU clocks : "<<clock_end-clock_start;
cout<<"\nReal Elapsed time (us) : "<<tod_end-tod_start;
}

void
timer::print_humain_friendly(){
	cout<<*this;
}

timer::timer(){
}
timer::~timer(){
}

inline 	double	
timer::elapsed(long long& cycles, double& clocks,double& usecs){
	cycles=cycle_end-cycle_start;
	clocks=clock_end-clock_start;
	usecs  =tod_end-tod_start;
return usecs;
}

double	
timer::start(){
	struct timeval tv;
gettimeofday(&tv,NULL);
tod_start=tv.tv_sec*10E6+tv.tv_usec;

return tod_start;
}

double	
timer::end(){	
struct timeval tv;
gettimeofday(&tv,NULL);
tod_end=tv.tv_sec*10E6+tv.tv_usec;
return tod_end;
}
void	
timer::print(bool humain){
if(humain){
	print_humain_friendly();
	return;
	}
print_machine();
}

ostream&	operator<<(ostream& out, const timer& t){
double	elapsed=t.tod_end-t.tod_start;
int	m,s,ms,us;
m=(int)(elapsed/10E6/60);
s=(int)((elapsed-m*10E6*60)/10E6);
ms=(int)((elapsed-s*10E6-m*10E6*60)/10E3 );
us=(int)(elapsed-s*10E6-m*10E6*60-ms*10E3);

out<<"\n\nElapsed time (humain)\t: "<<m<<"(m),\t "<<s<<"(s),\t "<<ms<<"(ms),\t "<<us<<"(us).";
out<<"\nElapsed (machine)\t: "<<(long long)elapsed<<"(us)\n";
return out;
}
